//
//  MenkDatePicker.m
//  CDatePicker
//
//  Created by Mac on 2023/12/8.
//

#import "MenkDatePicker.h"
#import <MenkView.h>
#import <Masonry.h>
#import "UIColor+Kyes.h"
#import "NSDate+Extensions.h"
#import "MKMacro.h"
#import "MKDaysItem.h"
#import "MKDateModel.h"
#import "MKPopoverView.h"

@interface MenkDatePicker ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(strong,nonatomic) UILabel *yearLeft;
@property(strong,nonatomic) UILabel *yearRight;

@property(strong,nonatomic) UILabel *monthLeft;
@property(strong,nonatomic) UILabel *monthRight;


@property(strong,nonatomic) MenkView *titleView;
@property(strong,nonatomic) NSArray *monthTitle;

@property(strong,nonatomic) UICollectionView *collectionView;
@property(strong,nonatomic) NSMutableArray *dataSource;

@property(strong,nonatomic) NSDate *currentDate;



@property(strong,nonatomic) UILabel *title_month;
@property(strong,nonatomic) UILabel *title_year;


/// 今天的日期
@property(strong,nonatomic) NSDate *today;
/// 选择的日期
@property(strong,nonatomic) MKDateModel *selectModel;

///
@property(strong,nonatomic) MKPopoverView *popview;





@end
static NSString *const ID_DAYS = @"MenkDatePicker";
@implementation MenkDatePicker


- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]){
        UIView *top_view = [[UIView alloc]init];
        top_view.backgroundColor = [UIColor hexColor:@"#A02B1F"];
        [self addSubview:top_view];
        
        [top_view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self);
            make.height.mas_equalTo(60);
        }];
        
        self.yearLeft = [[UILabel alloc]init];
        self.yearLeft.text = @"<<";
        
        self.yearLeft.font = [UIFont systemFontOfSize:20];
        self.yearRight.font = [UIFont systemFontOfSize:20];
        self.monthLeft.font = [UIFont systemFontOfSize:20];
        self.monthRight.font = [UIFont systemFontOfSize:20];
        
        
        
        self.yearRight = [[UILabel alloc]init];
        self.yearRight.text = @">>";
        
        self.monthLeft = [[UILabel alloc]init];
        self.monthLeft.text = @"<";
        
        self.monthRight = [[UILabel alloc]init];
        self.monthRight.text = @">";
        
        self.yearLeft.textAlignment = NSTextAlignmentCenter;
        self.yearRight.textAlignment = NSTextAlignmentCenter;
        
        self.monthLeft.textAlignment = NSTextAlignmentCenter;
        self.monthRight.textAlignment = NSTextAlignmentCenter;
        
        self.yearLeft.textColor = [UIColor whiteColor];
        self.yearRight.textColor = [UIColor whiteColor];
        self.monthLeft.textColor = [UIColor whiteColor];
        self.monthRight.textColor = [UIColor whiteColor];
        
        [top_view addSubview:self.yearLeft];
        [top_view addSubview:self.yearRight];
        [top_view addSubview:self.monthRight];
        [top_view addSubview:self.monthLeft];
        
        [self.yearLeft mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(top_view.mas_left).offset(18);
            make.centerY.equalTo(top_view);
        }];
        
        [self.monthLeft mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.yearLeft.mas_right).offset(10);
            make.centerY.equalTo(top_view);
        }];

        [self.yearRight mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(top_view).offset(-18);
            make.centerY.equalTo(top_view);
        }];

        [self.monthRight mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.yearRight.mas_left).offset(-10);
            make.centerY.equalTo(top_view);
        }];
        
        
        
        
        
        UILabel *yearLabel = [[UILabel alloc]init];
        yearLabel.textColor = [UIColor whiteColor];
        [top_view addSubview:yearLabel];
        self.title_year = yearLabel;
        
        [yearLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(top_view.mas_centerX).offset(-40);
            make.height.top.equalTo(top_view);
        }];
        
        MenkView *mkYearView = [[MenkView alloc]initWithFrame:CGRectZero];
        mkYearView.textColor = [UIColor whiteColor];
        mkYearView.numberOfLines = 1;
        mkYearView.textAlignment = MKTextAlignmentCenter;
        mkYearView.font = MenkQaganTig(20);
        mkYearView.lineSpacing = 20;
        mkYearView.text = @"";
        mkYearView.backgroundColor = [UIColor clearColor];
        [top_view addSubview:mkYearView];
        
        [mkYearView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(top_view.mas_centerX).offset(0);
            make.height.top.equalTo(top_view);
            make.width.equalTo(@(40));
        }];
        
        UILabel *monthLable = [[UILabel alloc]init];
        monthLable.textColor = [UIColor whiteColor];
        [top_view addSubview:monthLable];
        self.title_month = monthLable;
        
        [monthLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(top_view.mas_centerX).offset(10);
            make.height.top.equalTo(top_view);
            make.width.mas_equalTo(20);
        }];
        
        MenkView *mkMonthView = [[MenkView alloc]initWithFrame:CGRectZero];
        mkMonthView.textColor = [UIColor whiteColor];
        mkMonthView.numberOfLines = 1;
        mkMonthView.textAlignment = MKTextAlignmentCenter;
        mkMonthView.font = MenkQaganTig(20);
        mkMonthView.lineSpacing = 20;
        mkMonthView.text = @"";
        mkMonthView.backgroundColor = [UIColor clearColor];
        [top_view addSubview:mkMonthView];
        
        [mkMonthView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(monthLable.mas_right).offset(0);
            make.height.top.equalTo(top_view);
            make.width.equalTo(@(40));
        }];
        
#pragma mark - 周表
        UIView *view = nil;
        
        for (int i = 0; i < self.monthTitle.count; i++) {
            
            MenkView *weekView = [[MenkView alloc]initWithFrame:CGRectZero];
            weekView.textColor = [UIColor blackColor];
            weekView.numberOfLines = 0;
            weekView.textAlignment = MKTextAlignmentTopCenter;
            weekView.font = MenkQaganTig(14);
            weekView.lineSpacing = 20;
            weekView.text = self.monthTitle[i];
            weekView.backgroundColor = [UIColor clearColor];
//            weekView.backgroundColor = MK_RANDOMCOLOR;
            [self addSubview:weekView];
            
            [weekView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.equalTo(self).multipliedBy(1.0 / 7.0);
                make.top.equalTo(top_view.mas_bottom).offset(18);
                make.height.mas_equalTo(35);
                // 左边距离父视图的左边是 6 个 1/7
                make.left.equalTo(view ? view.mas_right : self.mas_left);
            }];
            view = weekView;
            
        }
        
        [self addSubview:self.collectionView];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(view.mas_bottom).offset(18);
            make.left.right.bottom.equalTo(self);
        }];
        
        
        
        
        self.yearLeft.userInteractionEnabled = YES;
        self.yearRight.userInteractionEnabled = YES;
        self.monthLeft.userInteractionEnabled = YES;
        self.monthRight.userInteractionEnabled = YES;
        
        yearLabel.userInteractionEnabled = YES;
        monthLable.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *monthLeftGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(monthLeftClick)];
        [self.monthLeft addGestureRecognizer:monthLeftGes];
        
        UITapGestureRecognizer *monthRightGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(monthRightClick)];
        [self.monthRight addGestureRecognizer:monthRightGes];

        UITapGestureRecognizer *yearLeftGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(yearLeftClick)];
        [self.yearLeft addGestureRecognizer:yearLeftGes];
        
        UITapGestureRecognizer *yearRightGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(yearRightClick)];
        [self.yearRight addGestureRecognizer:yearRightGes];
        
        
        UITapGestureRecognizer *monthTitleGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(monthTitleClick)];
        [monthLable addGestureRecognizer:monthTitleGes];
        
        UITapGestureRecognizer *yearTitleGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(yearTitleClick)];
        [yearLabel addGestureRecognizer:yearTitleGes];
        
        
        
        NSDate *date = [[NSDate alloc] init];
        self.today = date;
        [self get_resource:date];
        
        self.popview = [[MKPopoverView alloc]init];
        self.popview.hidden = YES;
        [self addSubview:self.popview];
        
        [self.popview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.title_month.mas_bottom);
            make.centerX.equalTo(self.title_month);
            make.width.mas_equalTo(80);
            make.height.mas_equalTo(280);
        }];
        
        __weak typeof(self) weakSelf = self;
        self.popview.select_pop = ^(NSInteger num) {
            weakSelf.popview.hidden = YES;
            
            if (weakSelf.popview.yearMode){
                // 创建一个日历对象
                NSCalendar *calendar = [NSCalendar currentCalendar];

                // 创建一个日期组件对象
                NSDateComponents *components = [[NSDateComponents alloc] init];
                [components setYear:num];
                [components setMonth:weakSelf.selectModel.month];
                [components setDay:1];

                // 从日期组件中获取日期
                NSDate *date = [calendar dateFromComponents:components];
                [weakSelf get_resource:date];
            }else{
                // 创建一个日历对象
                NSCalendar *calendar = [NSCalendar currentCalendar];

                // 创建一个日期组件对象
                NSDateComponents *components = [[NSDateComponents alloc] init];
                [components setYear:weakSelf.selectModel.year];
                [components setMonth:num];
                [components setDay:1];

                // 从日期组件中获取日期
                NSDate *date = [calendar dateFromComponents:components];
                [weakSelf get_resource:date];
            }
        };
    }
    return self;
}

- (void)monthTitleClick{
    
    [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium] impactOccurred];
    
    if (!self.popview.hidden && !self.popview.yearMode){
        self.popview.hidden = YES;
        return;
    }
    self.popview.hidden = NO;
    
    self.popview.yearMode = NO;
    [self.popview mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.title_month.mas_bottom);
        make.centerX.equalTo(self.title_month);
        make.width.mas_equalTo(80);
        make.height.mas_offset(280);
    }];
}

- (void)yearTitleClick{
    
    [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium] impactOccurred];
    
    if (!self.popview.hidden && self.popview.yearMode){
        self.popview.hidden = YES;
        return;
    }
    
    self.popview.hidden = NO;
    self.popview.yearMode = YES;
    [self.popview mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.title_year.mas_bottom);
        make.centerX.equalTo(self.title_year);
        make.width.mas_equalTo(80);
        make.height.mas_offset(280);
//        make.edges.equalTo(self);
    }];
    
}
- (void)monthLeftClick{
    
    [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium] impactOccurred];
    
    // 创建一个日历对象
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    // 创建一个日期组件对象
    NSDateComponents *components = [[NSDateComponents alloc] init];
    
    
    // 获取上一个月的日期
    [components setMonth:-1];
    NSDate *previousMonthDate = [calendar dateByAddingComponents:components toDate:self.currentDate options:0];
    
    [self get_resource:previousMonthDate];
}

- (void)monthRightClick{
    
    [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium] impactOccurred];
    
    // 创建一个日历对象
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    // 创建一个日期组件对象
    NSDateComponents *components = [[NSDateComponents alloc] init];
    
    // 获取下一个月的日期
    [components setMonth:1];
    NSDate *nextMonthDate = [calendar dateByAddingComponents:components toDate:self.currentDate options:0];
    
    [self get_resource:nextMonthDate];
}

- (void)yearLeftClick{
    
    [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium] impactOccurred];
    
    // 创建一个日历对象
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    // 创建一个日期组件对象
    NSDateComponents *components = [[NSDateComponents alloc] init];
    
    
    // 获取上一个月的日期
    [components setYear:-1];
    NSDate *previousMonthDate = [calendar dateByAddingComponents:components toDate:self.currentDate options:0];
    
    [self get_resource:previousMonthDate];
}

- (void)yearRightClick{
    
    [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium] impactOccurred];
    
    // 创建一个日历对象
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    // 创建一个日期组件对象
    NSDateComponents *components = [[NSDateComponents alloc] init];
    
    // 获取下一个月的日期
    [components setYear:1];
    NSDate *nextMonthDate = [calendar dateByAddingComponents:components toDate:self.currentDate options:0];
    
    [self get_resource:nextMonthDate];
}

- (void)get_resource:(NSDate *)date{
    
    
    
//    NSTimeZone *beijingTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
//    [NSTimeZone setDefaultTimeZone:beijingTimeZone];
    
    self.currentDate = date;
    
//    NSDate *date = [[NSDate alloc]init];
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    [calendar setTimeZone:beijingTimeZone];
    
    // 获取当前的年
    NSInteger year = [date currentYear];
    NSInteger month = [date currentMonth];
    NSInteger day = [date currentDay];
    
    if (!self.selectModel){
        MKDateModel *model = [[MKDateModel alloc]init];
        model.year = year;
        model.month = month;
        model.day = day;
        self.selectModel = model;
    }
    
    
    NSInteger today_year = [self.today currentYear];
    NSInteger today_month = [self.today currentMonth];
    NSInteger today_day = [self.today currentDay];
    
    self.title_year.text = [NSString stringWithFormat:@"%ld",year];
    self.title_month.text = [NSString stringWithFormat:@"%ld",month];
    
    // 下一年
    NSInteger below_year = year;
    //上一年
    NSInteger above_year = year;
    
    NSInteger day_count = [NSDate numberOfDaysInMonth:month year:year];
    
    // 一号是周几
    NSInteger weekOfOneDay = [NSDate dayOfWeekForYear:year month:month day:1];
    if (weekOfOneDay == 1){
        weekOfOneDay = 7;
    }else{
        weekOfOneDay -= 1;
    }
    
    //下一个月
    NSInteger below_month = month + 1;
    
    if (below_month > 12){
        below_month = 1;
        below_year += 1;
    }
    
    
    
    // 上一个月
    NSInteger above_month = month - 1;
    //above_month = above_month <= 0 ? 12 : above_month;
    
    if (above_month <= 0){
        above_month = 12;
        above_year -= 1;
    }
    
    
    NSMutableArray *aboveModels = [NSMutableArray array];
    NSMutableArray *belowModels = [NSMutableArray array];
    NSMutableArray *currentModels = [NSMutableArray array];
    
    // 如果一号不是周一 那么
    if (weekOfOneDay != 1){
        NSInteger add_count = weekOfOneDay - 1;
        
        // 获取上一个月有多少天
        NSInteger above_month_day_count = [NSDate numberOfDaysInMonth:above_month year:above_year];
        
        for (int i = 0; i < add_count; i++) {
            MKDateModel *model = [[MKDateModel alloc]init];
            model.day = above_month_day_count - (add_count - 1 - i);
            model.year = year;
            model.month = above_month;
            [aboveModels addObject:model];
            
            if (model.day == self.selectModel.day && model.year == self.selectModel.year && model.month == self.selectModel.month){
                model.selectDay = YES;
            }
        }
    }
    
    
    // 获取本月数据
    for (int i = 1; i <= day_count; i++) {
        MKDateModel *model = [[MKDateModel alloc]init];
        model.day = i;
        model.year = year;
        model.month = month;
        
        if (year == today_year && month == today_month && i == today_day){
            model.today = YES;
        }
        
        if (model.day == self.selectModel.day && model.year == self.selectModel.year && model.month == self.selectModel.month){
            model.selectDay = YES;
        }
        
        [currentModels addObject:model];
        
        
    }
    
    
    // 上一月的尾 + 这个月的数据 是否能填满 7 * 6
    NSInteger models_count = aboveModels.count + currentModels.count;
    if (models_count < 7 * 6){
        for (int i = 1; i <= (7 * 6) - models_count; i++) {
            MKDateModel *model = [[MKDateModel alloc]init];
            model.day = i;
            model.year = below_year;
            model.month = below_month;
            [belowModels addObject:model];
            
            if (model.day == self.selectModel.day && model.year == self.selectModel.year && model.month == self.selectModel.month){
                model.selectDay = YES;
            }
        }
    }
    
    
    [self.dataSource removeAllObjects];
    
    [self.dataSource addObjectsFromArray:aboveModels];
    [self.dataSource addObjectsFromArray:currentModels];
    [self.dataSource addObjectsFromArray:belowModels];
    
    [self.collectionView reloadData];
    
}

#pragma mark data_source  delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MKDaysItem *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID_DAYS forIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium] impactOccurred];
    MKDateModel *model = self.dataSource[indexPath.item];
    self.selectModel = model;
    
    [self get_resource:self.currentDate];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.frame.size.width / 7.0, self.frame.size.width / 7.0);
}


- (NSArray *)monthTitle{
    if (!_monthTitle) {
        _monthTitle = @[@"",@"",@"",@"",@"",@"",@""];
    }
    return _monthTitle;
}


- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
    
- (UICollectionView * )collectionView{
    if (!_collectionView) {
        // 创建 CollectionViewFlowLayout
        UICollectionViewFlowLayout *collectionViewLayout = [[UICollectionViewFlowLayout alloc] init];
        collectionViewLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        collectionViewLayout.minimumLineSpacing = 0;
        collectionViewLayout.minimumInteritemSpacing = 0;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:collectionViewLayout];
        
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[MKDaysItem class] forCellWithReuseIdentifier:ID_DAYS];
    }
    return _collectionView;
}



@end
